#!/usr/bin/python
# -*- utf-8 -*-

import os,time
from argtools import command, argument
import threadpool
import json

cnt_threadpool=30
cnt_resdir="res"

def opendmm_id(arg):
    #print "==================================="
    #print arg
    id=arg[0]
    no_downed=arg[1]
    pre,fix=id.split("-")
    ijsonp=cnt_resdir+"/"+pre+"/"+id+'/'
    ijson=cnt_resdir+"/"+pre+"/"+id+"/"+"info.json"
    ijpg=cnt_resdir+"/"+pre+"/img/"+id+".jpg"
    if no_downed:
        if os.path.exists(ijsonp) and os.path.exists(ijson) and os.path.exists(ijpg): 
            print "thread: %s [exists]"%(id)
            return
    else:
        print "thread: %s"%(id)
    re=os.popen("opendmm "+id).readlines()
    data=" ".join(re)
    try:
        s=json.loads(data)
        if not os.path.exists(ijsonp):
            os.mkdir(ijsonp)
        fd=open(ijson,"w")
        fd.write(data)
        fd.close()
        url=s["cover_image"]
        os.popen("wget -O ./%s/%s/img/%s.jpg %s >/dev/null 2>&1"%(cnt_resdir,pre,id,url))
        print "thread: %s [downed]"%(id)
    except:
        print "thread: %s [ERR]"%(id)

def AvIDPool(idPrefix,min,max,isdown=False):
    List=[]
    for i in range(int(min), int(max)):
        List.append(["%s-%03d" % (idPrefix, i), isdown])
    return List
    
def AvIDPoolC(idPrefix,strval,isdown=False):
    List=[]
    T=strval.split(',')
    for i in T:
        try:
            List.append(["%s-%03d" % (idPrefix, int(i)), isdown])
        except:
            print "    err custom av id:",i
    return List

@command
@argument('-a', '--av-name', default="svdvd", help='av name id')
@argument('-m', '--min-id', default=1, help='start min id')
@argument('-x', '--max-id', default=1000, help='end max id')
@argument('-n', '--no-downloaded', action='store_true', default=False, help='exist no download')
@argument('-t', '--thread-num', default=cnt_threadpool, help='max thread num')
@argument('-c', '--custom-id', type=str, default="", help='set custom down av id')
def runapp(args):
    if not os.path.exists(cnt_resdir): os.mkdir(cnt_resdir+'/')
    if not os.path.exists(cnt_resdir+"/"+args.av_name+'/'):
        os.mkdir(cnt_resdir+"/"+args.av_name+'/')
    if not os.path.exists(cnt_resdir+"/"+args.av_name+'/img'):
        os.mkdir(cnt_resdir+"/"+args.av_name+'/img')
    if args.thread_num < 1 : args.thread_num=1
    pool = threadpool.ThreadPool(args.thread_num)
    isdown=args.no_downloaded
    if len(args.custom_id):
        L=AvIDPoolC(args.av_name,args.custom_id,isdown)
    else:
        L=AvIDPool(args.av_name,args.min_id,args.max_id,isdown)
    requests = threadpool.makeRequests(opendmm_id,L)
    [pool.putRequest(req) for req in requests]
    pool.wait()

if __name__ == "__main__":
    command.run()
